package logic

import (
	"context"
	"fmt"
	"sends/models/mysqlinit"
	"sends/models/redisinit"
	"sends/sendrpc/internal/svc"
	"sends/sendrpc/sendrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *sendrpc.RegisterRequest) (*sendrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user mysqlinit.User

	mysqlinit.DB.Debug().Where("account = ?", in.Account).Find(&user)

	if user.Account != in.Account {

		result, _ := redisinit.Client.Get("SendSms" + in.Account + "Register").Result()
		if in.SendSms != result {
			return nil, fmt.Errorf("注册短信验证码错误")
		}

		m := mysqlinit.User{

			Account: in.Account,
		}
		mysqlinit.DB.Debug().Create(&m)

	} else {

		result, _ := redisinit.Client.Get("SendSms" + in.Account + "Register").Result()
		if in.SendSms != result {
			return nil, fmt.Errorf("登录短信验证码错误")
		}

	}

	return &sendrpc.RegisterResponse{
		Id: int64(user.ID),
	}, nil
}
